<?php
declare (strict_types=1);

namespace app\admin\controller;

use ffhome\upload\Uploadfile;
use think\facade\Cache;
use think\facade\Db;

class Ajax extends CommonController
{
    /**
     * 初始化后台接口地址
     */
    public function init()
    {
        return json(authService()->init());
    }

    /**
     * 清理缓存接口
     */
    public function clearCache()
    {
        Cache::clear();
        $this->success(lang('index.clear_success'));
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file' => $this->request->file('file'),
            'prefix' => $this->request->post('prefix', 'up'),
        ];
        $uploadConfig = sysConfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|' . lang('upload.upload_type_fail') => "in:{$uploadConfig['upload_allow_type']}",
            'file|' . lang('upload.file') => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->setPrefix($data['prefix'])
                ->setCreateBy(currentUserId())
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            $this->success($upload['msg'], $upload);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 上传图片至编辑器
     */
    public function uploadEditor()
    {
        $data = [
            'upload_type' => $this->request->post('upload_type'),
            'file' => $this->request->file('upload'),
            'prefix' => $this->request->post('prefix', 'editor'),
        ];
        $uploadConfig = sysConfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        $rule = [
            'upload_type|' . lang('upload.upload_type_fail') => "in:{$uploadConfig['upload_allow_type']}",
            'file|' . lang('upload.file') => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
        ];
        $this->validate($data, $rule);
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->setPrefix($data['prefix'])
                ->setCreateBy(currentUserId())
                ->setWidth(900)
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        if ($upload['save'] == true) {
            return json([
                'error' => [
                    'message' => lang('upload.success'),
                    'number' => 201,
                ],
                'fileName' => '',
                'uploaded' => 1,
                'url' => $upload['url'],
            ]);
        } else {
            $this->error($upload['msg']);
        }
    }

    /**
     * 获取上传文件列表
     */
    public function getUploadFiles()
    {
        $get = $this->request->get();
        $page = isset($get['page']) && !empty($get['page']) ? intval($get['page']) : 1;
        $limit = isset($get['limit']) && !empty($get['limit']) ? intval($get['limit']) : 10;
        $title = isset($get['title']) && !empty($get['title']) ? $get['title'] : null;
        $count = $this->getUploadfileModel($title)->count();
        $list = $this->getUploadfileModel($title)
            ->page($page, $limit)
            ->order(['id' => 'desc'])
            ->select()->toArray();
        return $this->successPage($count, $list);
    }

    private function getUploadfileModel($title)
    {
        $model = Db::name('system_uploadfile');
        if (!empty($title)) {
            $model->where('original_name', 'like', "%{$title}%");
        }
        return $model;
    }
}
